package com.kylin.module.ad.business;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;

import com.kylin.common.Constants;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.util.Config;
import com.kylin.common.util.MemObjFactory;
import com.kylin.common.util.UUID;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.hibernate.CriteriaInfo;
import com.kylin.hibernate.PropertyCondition;
import com.kylin.module.ad.forms.ADForm;
import com.kylin.module.ad.forms.ADTypeForm;
import com.kylin.module.ad.orm.AD;
import com.kylin.module.ad.orm.ADType;

/**
 * 广告模块的业务逻辑类
 * @author lzh
 *
 */
public class ADBlogic {

	protected static Logger log = Logger.getLogger(ADBlogic.class);

	/**
	 * 增加新的广告类型
	 * @param form
	 * @throws BusinessException
	 */
	public void addADType(ADTypeForm form) throws BusinessException {
		log.debug("增加新的广告类型" + form.getName());
		ADType exmp = new ADType();
		exmp.setMark(form.getMark());
		List exist = BaseHibernateDAO.findByExample(exmp);
		if(exist != null && exist.size() >0)
			throw new BusinessException("已存在相同的广告类型标识符："+form.getMark());
		
		exmp = new ADType();
		exmp.setName(form.getName());
		exist = BaseHibernateDAO.findByExample(exmp);
		if(exist != null && exist.size() >0)
			throw new BusinessException("已存在同名的广告类型："+form.getName());
		
		ADType obj = new ADType();
		obj.setName(form.getName());
		obj.setMark(form.getMark());
		obj.setShowtype(form.getShowtype());
		if(!"".equals(form.getHeight()) && form.getHeight()!=null)
			obj.setHeight(new Integer(form.getHeight()));
		if(form.getWidth()!=null&& !form.getWidth().equals(""))
			obj.setWidth(new Integer(form.getWidth()));
		obj.setFiletype(form.getFiletype());
		obj.setActive(Constants.ACTIVE_ON);
		obj.setCreatedon(new Date());
//obj.setLanguage(form.getLanguage());
//obj.setOrdering(form.getOrdering());

		BaseHibernateDAO.save(obj);

	}

	/**
	 * 修改广告类型
	 * @param form
	 * @throws BusinessException
	 */
	public ADType updateADType(ADTypeForm form) throws BusinessException {
		log.debug("修改广告类型" + form.getName());
		ADType obj = (ADType) BaseHibernateDAO.findById(ADType.class, form.getId());
		if (form.getMark() != null && !form.getMark().equals(obj.getMark())) {
			ADType exmp = new ADType();
			exmp.setMark(form.getMark());
			List exist = BaseHibernateDAO.findByExample(exmp);
			if (exist != null && exist.size() > 0)
				throw new BusinessException("已存在相同的广告类型标识符：" + form.getMark());
		}
		if (form.getName() != null && !form.getName().equals(obj.getName())) {
			ADType exmp = new ADType();
			exmp.setName(form.getName());
			List exist = BaseHibernateDAO.findByExample(exmp);
			if (exist != null && exist.size() > 0)
				throw new BusinessException("已存在同名的广告类型：" + form.getName());
		}
		obj.setName(form.getName());
		obj.setMark(form.getMark());
		obj.setShowtype(form.getShowtype());
		if(!"".equals(form.getHeight()) && form.getHeight()!=null)
		obj.setHeight(new Integer(form.getHeight()));
		if(form.getWidth()!=null&& !form.getWidth().equals(""))
		obj.setWidth(new Integer(form.getWidth()));
		obj.setFiletype(form.getFiletype());
		obj.setActive(Constants.ACTIVE_ON);
		obj.setLastupdatedon(new Date());
		// obj.setLanguage(form.getLanguage());
		// obj.setOrdering(form.getOrdering());

		BaseHibernateDAO.update(obj);
		return obj;
	}

	/**
	 * 增加新的广告
	 * @param form
	 * @throws BusinessException
	 * @throws IOException
	 * @throws IOException
	 */
	public void addAD(ADForm form) throws BusinessException, IOException, IOException{
		log.debug("增加新的广告" + form.getName());
		AD obj = new AD();
		
		FormFile file = form.getFile();
		if(file == null || file.getFileSize() < 1 || "".equals(file.getFileName()) )
			throw new BusinessException("没有上传广告的媒体文件");
		obj.setAdtype((ADType)BaseHibernateDAO.findById(ADType.class, form.getAdtype()) );
		String fileDir= form.getAppPath() + "/" + obj.getAdtype().getMark() +"/" ;
		File dir = new File(fileDir);
		if(!dir.exists())
			dir.mkdirs();
		String webPath = form.getLanguage()+UUID.create()+getFileExt(file.getFileName());
		saveFile(file.getInputStream(), fileDir + webPath);
		obj.setFileurl(webPath);
		obj.setName(form.getName());
		obj.setLink(form.getLink());
		obj.setMemo(form.getMemo());
		obj.setOwner(form.getOwner());
		obj.setLanguage(form.getLanguage());
		obj.setOrdering(form.getOrdering());
		obj.setCreatedon(new Date());
		obj.setHits(new Integer(0));
		obj.setActive(Constants.ACTIVE_ON);
		if(form.getEndtime() != null && form.getEndtime().length()==10)
			try {
				SimpleDateFormat sformat = new SimpleDateFormat("yyyy-mm-dd");
				obj.setEndtime(sformat.parse(form.getEndtime()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		BaseHibernateDAO.save(obj);
		MemObjFactory.reloadAD(obj.getAdtype().getMark(), obj.getLanguage());
	}

	/**
	 * 修改广告信息
	 * @param form
	 * @throws BusinessException
	 * @throws IOException
	 * @throws IOException
	 */
	public AD updateAD(ADForm form) throws BusinessException, IOException, IOException{
		log.debug("修改广告信息 " + form.getName());
		AD obj = (AD)BaseHibernateDAO.findById(AD.class, form.getId());		
//不能改类型		obj.setAdtype((ADType)BaseHibernateDAO.findById(ADType.class, form.getAdtype()) );
		FormFile file = form.getFile();
		if(file != null && file.getFileSize() > 1 && !"".equals(file.getFileName()) ){
			String fileDir= form.getAppPath() + "/" + obj.getAdtype().getMark() +"/" ;
			File dir = new File(fileDir);
			if(!dir.exists())
				dir.mkdirs();
			String webPath = form.getLanguage() + UUID.create()+getFileExt(file.getFileName());
			saveFile(file.getInputStream(), fileDir + webPath);
			obj.setFileurl(webPath);
		}
		obj.setName(form.getName());
		obj.setLink(form.getLink());
		obj.setMemo(form.getMemo());
		obj.setOwner(form.getOwner());
		obj.setLanguage(form.getLanguage());
		obj.setOrdering(form.getOrdering());
		if(form.getEndtime() != null && form.getEndtime().length()==10)
			try {
				SimpleDateFormat sformat = new SimpleDateFormat("yyyy-mm-dd");
				obj.setEndtime(sformat.parse(form.getEndtime()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		obj.setLastupdatedon(new Date());
//		obj.setActive(Constants.ACTIVE_ON);
		BaseHibernateDAO.update(obj);
		MemObjFactory.reloadAD(obj.getAdtype().getMark(), obj.getLanguage());
		return obj;
	}
	
	public ADType getADTypeById(Long id) throws BusinessException{
		return (ADType)BaseHibernateDAO.findById(ADType.class, id);		
	}
	
	public AD getADById(Long id) throws BusinessException{
		return (AD)BaseHibernateDAO.findById(AD.class, id);		
	}
	/**
	 * 传入文件名，返回此文件名的扩展名
	 * 扩展名带有前面的 . 例如 .jpg
	 * @param fileName
	 * @return
	 */private static String getFileExt(String fileName){
		String ext = "";
		int idx = fileName.lastIndexOf(".");
		if (idx > 0 && idx < fileName.length()) {
			ext = fileName.substring(idx , fileName.length());
		}
		return ext;
	}
	
	/**
	 * 将文件保存到磁盘
	 * @param imgType 不同种类文件,按此分目录,参见 Constants
	 * @param in 输入数据流
	 * @param fileName 文件保存的物理路径
	 * @throws BusinessException 
	 * @throws IOException
	 */
	private static void saveFile(InputStream in,String adFilePath) throws BusinessException {
		log.info("保存上传文件路径："+adFilePath);
		FileOutputStream fout = null;
		try {
			fout = new FileOutputStream(adFilePath);
		int b = in.read();
		while(b != -1){
			fout.write(b);
			b = in.read();
		}
		fout.close();
		} catch (IOException e) {
			throw new BusinessException(e);
		}finally{
			if(fout!=null)
				try {
					fout.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	
	/**
	 * 根据广告类型的标志获取广告类型对象
	 * @param mark
	 * @return
	 * @throws BusinessException
	 */
	public ADType getTypeByMark(String mark) throws BusinessException{
		ADType examp = new ADType();
		examp.setMark(mark);
		List list = BaseHibernateDAO.findByExample(examp);
		if(list == null || list.size() < 1)
			return null;
		else
			return (ADType)list.get(0);
	}

	/**
	 * 
	 * @param type
	 * @param language
	 * @param order   第几个广告（按AD对象的排序号从小到大）
	 * @return
	 * @throws BusinessException
	 */
	public ADType getADTypeADs(String typeMark,String language) throws BusinessException{
		ADType adType = this.getTypeByMark(typeMark);
		if(adType == null)
			return null;
		List conditions = new LinkedList();  
		PropertyCondition cond1 = new PropertyCondition("adtype.mark", typeMark,PropertyCondition.OPERATOR_EQ );
		conditions.add(cond1);
		PropertyCondition cond2 = new PropertyCondition("language", language,PropertyCondition.OPERATOR_EQ );
		conditions.add(cond2);
		CriteriaInfo cinfo = new CriteriaInfo(AD.class, conditions);
		cinfo.setOrderby(Order.asc("ordering"));
		Criteria criteria = BaseHibernateDAO.getCriteriaFromInfo(cinfo);
		adType.setAdList(criteria.list());
		return adType;
	}
	
	public void saveAD(AD ad) throws BusinessException{
		BaseHibernateDAO.save(ad);
		MemObjFactory.reloadAD(ad.getAdtype().getMark(), ad.getLanguage());
	}
}
